package com.yc.sole.job;

import com.yc.sole.erp.dto.CustomerDto;
import com.yc.sole.erp.repository.CustomerRepository;
import com.yc.sole.erp.repository.ShipmentRepository;
import com.yc.sole.financial.repository.ReceiptRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author yizuomin
 * @date 2024/3/8 09:17
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class CustomerReceivablesJob {

    private final CustomerRepository customerRepository;
    private final ReceiptRepository receiptRepository;
    private final ShipmentRepository shipmentRepository;

    @Scheduled(cron = "0 30 10,22 * * ?")
    /*@Scheduled(cron = "0 * * * * ?")*/
    @Transactional(rollbackFor = Exception.class)
    public void run() {
        log.info("更新客户应收帐款-开始执行");
        Map<Long, BigDecimal> customerAmountMap = shipmentRepository.selectCustomerAmount();
        Map<Long, BigDecimal> customerReceiptAmount = receiptRepository.selectCustomerReceiptAmount(customerAmountMap.keySet());
        for (Long customerId : customerAmountMap.keySet()) {
            // 总应收款
            BigDecimal receivables = customerAmountMap.get(customerId);
            // 已收款
            BigDecimal receiptAmount = customerReceiptAmount.get(customerId);
            CustomerDto customerDto = new CustomerDto();
            customerDto.setId(customerId);
            customerDto.setReceivables(receivables);
            customerDto.setReceivedPayment(receiptAmount);
            customerRepository.updateById(customerDto);
        }
        log.info("更新客户应收帐款-执行结束");
    }
}
